<template>
  <div class="application-volunteer-container">
    <div class="page-header">
      <h2>入党志愿书管理</h2>
      <p>管理用户提交的入党志愿书</p>
    </div>

    <!-- 搜索和操作区域 -->
    <el-card class="search-card" shadow="hover">
      <div class="search-container">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="申请人">
            <el-input v-model="searchForm.name" placeholder="请输入申请人姓名" clearable @clear="handleInputClear('name')"
              @input="debounceSearch" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 100%"
              @change="handleStatusChange">
              <el-option label="待审核" :value="0" />
              <el-option label="已通过" :value="1" />
              <el-option label="已拒绝" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchVolunteers">
              <el-icon>
                <Search />
              </el-icon> 搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon>
                <Refresh />
              </el-icon> 重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 志愿书列表表格 -->
    <el-card class="table-card" shadow="hover" v-loading="loading">
      <el-table :data="volunteerList" border style="width: 100%" row-key="id">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="申请人" min-width="100" />
        <el-table-column prop="createTime" label="提交时间" min-width="170" :formatter="formatDateTime" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="审核时间" min-width="170" :formatter="formatDateTime" />
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="scope">
            <div class="action-buttons">
              <el-button size="small" type="primary" plain @click="handleView(scope.row)">
                <el-icon>
                  <View />
                </el-icon> 查看
              </el-button>
              <el-button size="small" type="success" plain @click="handleApprove(scope.row)"
                v-if="scope.row.status == 0">
                <el-icon>
                  <Check />
                </el-icon> 通过
              </el-button>
              <el-button size="small" type="danger" plain @click="handleReject(scope.row)" v-if="scope.row.status == 0">
                <el-icon>
                  <Close />
                </el-icon> 拒绝
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 查看志愿书详情对话框 -->
    <el-dialog v-model="dialogVisible" title="志愿书详情" width="800px" :close-on-click-modal="false">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="申请人">{{ currentVolunteer.name }}</el-descriptions-item>
        <el-descriptions-item label="提交时间">{{ formatDateTime(null, null, currentVolunteer.createTime)
        }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTagType(currentVolunteer.status)">
            {{ getStatusText(currentVolunteer.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="审核时间" :span="2">{{ currentVolunteer.updateTime ? formatDateTime(null, null,
          currentVolunteer.updateTime) : '-' }}</el-descriptions-item>
        <el-descriptions-item label="申请人基本情况" :span="2">
          <el-descriptions :column="2" size="small" border>
            <el-descriptions-item label="性别">{{ currentVolunteer.gender || '-' }}</el-descriptions-item>
            <el-descriptions-item label="民族">{{ currentVolunteer.ethnicity || '-' }}</el-descriptions-item>
            <el-descriptions-item label="学历">{{ currentVolunteer.eduLevel || '-' }}</el-descriptions-item>
            <el-descriptions-item label="家庭成员">{{ currentVolunteer.family || '-' }}</el-descriptions-item>
            <el-descriptions-item label="主要社会关系" :span="2">{{ currentVolunteer.socialRelations || '-'
            }}</el-descriptions-item>
            <el-descriptions-item label="关联用户ID">{{ currentVolunteer.userId || '-' }}</el-descriptions-item>
          </el-descriptions>
        </el-descriptions-item>
        <!-- <el-descriptions-item label="志愿书内容" :span="2">
          <div class="volunteer-content">
            {{ currentVolunteer.content || '暂无内容' }}
          </div>
        </el-descriptions-item> -->
        <!-- <el-descriptions-item label="志愿书附件" :span="2">
          <div class="attachment-list" v-if="currentVolunteer.attachments && currentVolunteer.attachments.length > 0">
            <div v-for="(attachment, index) in currentVolunteer.attachments" :key="index" class="attachment-item">
              <el-link type="primary" :href="attachment.url" target="_blank" :underline="false">
                <el-icon>
                  <Document />
                </el-icon>
                {{ attachment.name }}
              </el-link>
            </div>
          </div>
          <span v-else>暂无附件</span>
        </el-descriptions-item> -->
        <el-descriptions-item label="手写志愿书" :span="2" v-if="currentVolunteer.handwrittenDoc">
          <!-- <div class="handwritten-image">
            <el-image :src="currentVolunteer.handwrittenDoc" fit="contain"
              :preview-src-list="[currentVolunteer.handwrittenDoc]" />
          </div> -->
          <div class="document-preview">
            <el-icon class="document-icon">
              <Document />
            </el-icon>
            <div class="document-name">{{ getFileName(currentVolunteer.handwrittenDoc) }}</div>
            <el-button type="primary" @click="downloadFile(currentVolunteer.handwrittenDoc)">
              <el-icon>
                <Download />
              </el-icon> 下载附件
            </el-button>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="审核意见" :span="2">
          <div class="review-comment">
            {{ currentVolunteer.review || '暂无审核意见' }}
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="success" @click="handleApprove(currentVolunteer)"
            v-if="currentVolunteer.status == 0">通过</el-button>
          <el-button type="danger" @click="handleReject(currentVolunteer)"
            v-if="currentVolunteer.status == 0">拒绝</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog v-model="reviewDialogVisible" :title="reviewType === 'approve' ? '通过志愿书' : '拒绝志愿书'" width="500px"
      :close-on-click-modal="false">
      <el-form :model="reviewForm" ref="reviewFormRef" label-width="100px">
        <el-form-item label="审核意见" prop="review">
          <el-input v-model="reviewForm.review" type="textarea" :rows="4" placeholder="请输入审核意见" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="reviewDialogVisible = false">取消</el-button>
          <el-button :type="reviewType === 'approve' ? 'success' : 'danger'" @click="submitReview"
            :loading="submitting">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  Search, Refresh, View, Check, Close, Document
} from '@element-plus/icons-vue';
import {
  getVolunteerList,
  getVolunteerById,
  updateVolunteer
} from '@/api/volunteer';

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(false);
const volunteerList = ref([]);

// 搜索表单
const searchForm = reactive({
  name: '',
  status: ''
});
// 获取文件名
const getFileName = (fileUrl) => {
  const parts = fileUrl.split('/');
  console.log(parts);

  const file = parts[parts.length - 1];
  const nfile = file.substring(0, file.length - 1);
  return nfile;
};

// 下载文件
const downloadFile = (fileUrl) => {
  if (!fileUrl) {
    ElMessage.warning('文件URL不存在');
    return;
  }

  try {

    const nFileUrl = fileUrl.substring(0, fileUrl.length - 1);
    // 创建一个临时的a标签
    const link = document.createElement('a');
    link.href = nFileUrl;
    link.target = '_blank';

    // 从URL中提取文件名
    const fileName = getFileName(fileUrl);
    link.download = fileName;

    // 添加到body
    document.body.appendChild(link);

    // 触发点击
    link.click();

    // 移除元素
    document.body.removeChild(link);

    console.log("ssss");
    console.log(nFileUrl);
    console.log(fileName);

    ElMessage.success('下载请求已发送');
  } catch (error) {
    console.error('下载文件失败:', error);
    ElMessage.error('下载文件失败，请稍后重试');
  }
};

// 详情对话框
const dialogVisible = ref(false);
const currentVolunteer = ref({});

// 审核对话框
const reviewDialogVisible = ref(false);
const reviewType = ref(''); // 'approve' 或 'reject'
const reviewFormRef = ref(null);
const reviewForm = reactive({
  id: '',
  review: ''
});
const submitting = ref(false);

// 初始化加载数据
onMounted(() => {
  fetchVolunteers();
});

// 获取志愿书列表
const fetchVolunteers = async () => {
  loading.value = true;
  try {
    // 构建查询条件
    const queryData = {
      name: searchForm.name,
      status: searchForm.status
    };

    // 调用API获取数据
    const response = await getVolunteerList(queryData, currentPage.value, pageSize.value);

    if (response.data.code === 200) {
      const data = response.data.data || {};
      volunteerList.value = data.page?.records || [];
      total.value = data.total || 0;
    } else {
      ElMessage.error(response.data.msg || '获取志愿书列表失败');
      volunteerList.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取志愿书列表失败:', error);
    ElMessage.error('获取志愿书列表失败，请稍后重试');
    volunteerList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 搜索志愿书
const searchVolunteers = () => {
  currentPage.value = 1;
  fetchVolunteers();
};

// 重置搜索条件
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = '';
  });
  currentPage.value = 1;
  fetchVolunteers();
};

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchVolunteers();
};

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchVolunteers();
};

// 处理输入框清除
const handleInputClear = (key) => {
  searchForm[key] = '';
  fetchVolunteers();
};

// 处理状态变化
const handleStatusChange = () => {
  fetchVolunteers();
};

// 格式化日期时间
const formatDateTime = (row, column, cellValue) => {
  if (!cellValue) return '';
  const date = new Date(cellValue);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 获取状态标签类型
const getStatusTagType = (status) => {
  console.log(status);
  // 将字符串状态转为数字进行比较
  const statusCode = parseInt(status);

  switch (statusCode) {
    case 0: // PENGING_REVIEW
      return 'warning';
    case 1: // PASSED
      return 'success';
    case 2: // REJECTED
      return 'danger';
    default:
      // 兼容字符串状态值
      if (status === 'pending') return 'warning';
      if (status === 'approved') return 'success';
      if (status === 'rejected') return 'danger';
      return 'info';
  }
};

// 获取状态文本
const getStatusText = (status) => {
  // 如果状态为空或undefined，返回未知
  if (status === null || status === undefined) {
    return '未知';
  }

  // 将状态转换为字符串并转为小写，以便统一处理
  const statusStr = String(status).toLowerCase();

  // 定义状态映射
  const statusMap = {
    '0': '待审核',
    '1': '已通过',
    '2': '已拒绝',
    'pending': '待审核',
    'approved': '已通过',
    'rejected': '已拒绝'
  };

  // 返回映射的状态文本，如果没有匹配则返回未知
  return statusMap[statusStr] || '未知';
};

// 查看志愿书详情
const handleView = async (row) => {
  try {
    loading.value = true;
    // 调用API获取详细数据
    const response = await getVolunteerById(row.id);

    if (response.data.code === 200) {
      currentVolunteer.value = response.data.data.volunteer || {};
      dialogVisible.value = true;
    } else {
      ElMessage.error(response.data.msg || '获取志愿书详情失败');
    }
  } catch (error) {
    console.error('获取志愿书详情失败:', error);
    ElMessage.error('获取志愿书详情失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 处理通过志愿书
const handleApprove = (row) => {
  currentVolunteer.value = { ...row };
  reviewType.value = 'approve';
  reviewForm.id = row.id;
  reviewForm.review = '';
  reviewDialogVisible.value = true;
};

// 处理拒绝志愿书
const handleReject = (row) => {
  currentVolunteer.value = { ...row };
  reviewType.value = 'reject';
  reviewForm.id = row.id;
  reviewForm.review = '';
  reviewDialogVisible.value = true;
};

// 提交审核
const submitReview = async () => {
  submitting.value = true;
  try {
    // 构建提交数据
    const reviewData = {
      id: reviewForm.id,
      // 使用数字状态值：1-已通过，2-已拒绝
      status: reviewType.value === 'approve' ? 1 : 2,
      review: reviewForm.review,
    };

    // 调用API提交审核
    const response = await updateVolunteer(reviewData);

    if (response.data.code === 200) {
      ElMessage.success(reviewType.value === 'approve' ? '已通过志愿书' : '已拒绝志愿书');
      reviewDialogVisible.value = false;

      // 刷新列表
      fetchVolunteers();
    } else {
      ElMessage.error(response.data.msg || '提交审核失败');
    }
  } catch (error) {
    console.error('提交审核失败:', error);
    ElMessage.error('提交审核失败，请稍后重试');
  } finally {
    submitting.value = false;
  }
};

// 即时搜索
const debounceSearch = () => {
  fetchVolunteers();
};
</script>

<style scoped>
.application-volunteer-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 24px;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-header p {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}

.volunteer-content,
.review-comment {
  white-space: pre-line;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  max-height: 200px;
  overflow-y: auto;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.action-buttons .el-button {
  margin-left: 0 !important;
  width: 100%;
}

.handwritten-image {
  margin: 10px 0;
  text-align: center;
}

.handwritten-image .el-image {
  max-width: 100%;
  max-height: 300px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.introducer-item {
  margin-bottom: 8px;
}

.introducer-info {
  margin-left: 10px;
  color: #606266;
  font-size: 0.9em;
}

@media (max-width: 768px) {
  .search-container {
    flex-direction: column;
  }
}

.attachment-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.attachment-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.attachment-item .el-icon {
  margin-right: 4px;
}

.volunteer-content {
  white-space: pre-line;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  max-height: 200px;
  overflow-y: auto;
  line-height: 1.6;
}

.document-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.document-icon {
  font-size: 24px;
  color: #409EFF;
  margin-bottom: 5px;
}

.document-name {
  font-size: 14px;
  color: #303133;
  margin-bottom: 5px;
}
</style>